// graceUI/components/graceSingleSlider.js
Component({
  properties: {
    barHeight    : {type:Number, value:32},
		barWidth     : {type:Number, value:168},
		barColor     : {type:String, value:'#FFFFFF'},
		barBgColor   : {type:String, value:'linear-gradient(to right, #3688FF,#3688FF)'},
		bglineSize   : {type:Number, value:2},
		bglineColor  : {type:String, value:'rgba(54,136,255,0.5)'},
		bglineAColor : {type:String, value:'#3688FF'},
		barText      : {type:String, value:''},
		barTextSize  : {type:String, value:'20rpx'},
		borderRadius : {type:String, value:'32rpx'},
		canSlide     : {type:Boolean, value:true}
  },
  data: {
    left       : 0,
    startLeft  : 0,
    width      : 0,
    barWidthPX : 30
  },
  ready:function(){
    wx.getSystemInfo({
      success:(res) => {
        this.setData({barWidthPX:res.windowWidth/750*this.data.barWidth});
        this.init();
      }
    });
  },
  methods: {
    init : function(){
      wx.createSelectorQuery().in(this).select('#gracesgslider').fields(
        { size: true, rect:true }, (res) => {
          if(res == null){
						setTimeout(()=>{this.init();}, 100);
						return;
          }
          this.setData({startLeft:res.left, width:res.width});
        }
      ).exec();
    },
    touchstart : function (e) {
			if(!this.data.canSlide){return ;}
			var touch = e.touches[0] || e.changedTouches[0];
			this.changeBar(touch.pageX);
		},
		touchmove : function (e) {
			if(!this.data.canSlide){return ;}
			var touch = e.touches[0] || e.changedTouches[0];
			this.changeBar(touch.pageX);
		},
		touchend : function (e) {
			if(!this.data.canSlide){return ;}
			var touch = e.touches[0] || e.changedTouches[0];
			this.changeBar(touch.pageX, true);
		},
		changeBar : function(x, isEnd){
			var left = x - this.data.startLeft;
			if(left <= 0){
        this.setData({left:0});
				this.triggerEvent('change', 0);
			}else if(left + this.data.barWidthPX > this.data.width){
				left = this.data.width - this.data.barWidthPX;
        this.setData({left:left});
				this.triggerEvent('change', 100);
			}else{
        this.setData({left:left});
				var scale = this.data.left / (this.data.width - this.data.barWidthPX);
				this.triggerEvent('change', Math.round(scale * 100));
			}
		},
		setProgress : function (value){
			if(this.data.width < 1){ setTimeout(()=>{this.setProgress(value), 300}); return ;}
			if(value < 0){value = 0;}
			if(value > 100){value = 100;}
      this.setData({left:( value / 100 ) * (this.data.width - this.data.barWidthPX)});
		}
  }
})
